package com.zcs.app.lucky.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import cn.sxw.android.base.bean.GlideEngine
import cn.sxw.android.base.kt.BaseViewModel
import cn.sxw.android.base.utils.GlideStaticUtils
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.zcs.app.lucky.R
import com.zcs.app.lucky.base.BaseLuckyActivity
import com.zcs.app.lucky.databinding.ActivityAddPeopleBinding
import com.zcs.app.lucky.entity.LuckyPeople
import com.zcs.app.lucky.entity.TYPE_USER_NORMAL
import com.zcs.app.lucky.ui.clip.AvatarClipActivity

@SuppressLint("RestrictedApi")
class AddPeopleActivity : BaseLuckyActivity<ActivityAddPeopleBinding, BaseViewModel>() {
    override fun isLazyInit() = false
    private var avatar = ""
    private val user by lazy {
        LuckyPeople(TYPE_USER_NORMAL)
    }

    // 懒加载机制
    override fun onReady() {
        binding.toolbar.tvToolbarTitle.text = "添加成员"
    }

    override fun onInit() {
        initView()
        initObserve()
        initData()
    }

    @SuppressLint("CheckResult")
    fun onOpenAlbum() {
        rxPermissions.request(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe {
            if (it) {
                openAlbum()
            } else {
                // 授权失败
                onNeverAsk("文件存储/相机", withExit = true, true)
            }
        }
    }

    private fun openAlbum() {
        val fileProviderName = "$packageName.FileProvider"
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())
            .setPuzzleMenu(false) //不显示拼图按钮
            .setCleanMenu(false) //不显示清除按钮
            .setFileProviderAuthority(fileProviderName) //参数说明：见下方`FileProvider的配置`
            .setCount(1)
            .start(codePic)
    }

    private val codePic = 0x001// 选图
    private var mPicture: Photo? = null
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                codePic -> {// 处理图片
                    if (data == null) return
                    //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                    val resultPhotos: ArrayList<Photo> =
                        data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)
                    mPicture = resultPhotos.firstOrNull()
                    if (mPicture != null) {
                        val path = mPicture?.path ?: ""
                        if (path.isNotEmpty()) {
                            openClip(path)
                        }
                    }
                }
            }
        }
    }

    private fun openClip(path: String) {
        val intent = Intent(this, AvatarClipActivity::class.java)
        intent.putExtra("PATH", path)
        intent.putExtra("IS_CIRCLE", true)
        clipResultLauncher.launch(intent)
    }

    override fun initObserve() {
    }

    override fun initData() {
        // hide loading last
        hideLoading()
    }

    override fun initView() {
    }

    override fun addOnClickListener() {
        binding.toolbar.ivToolbarBack.setOnClickListener { onBackPressed() }
        binding.btnSave.setOnClickListener {
            onSave()
        }
        binding.ivAvatar.setOnClickListener {
            onOpenAlbum()
        }
    }

    private fun onSave() {
        val name = binding.etName.text.toString().trim()
        if (name.isEmpty()) {
            showToast("请输入姓名")
            return
        }
        if (avatar.isEmpty()) {
            showToast("请选择一张照片")
            return
        }
        val dept = binding.etDept.text.toString().trim()
        val phone = binding.etPhone.text.toString().trim()

        user.name = name
        user.avatar = avatar
        user.dept = dept
        user.phone = phone
        val intent = Intent()
        intent.putExtra("USER", user)
        setResult(Activity.RESULT_OK, intent)
        killMyself()
    }

    private lateinit var clipResultLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // registerForActivityResult  注:必须在onCreate内注册，有点劝退的感觉
        clipResultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == Activity.RESULT_OK) {
                    avatar = it.data?.getSerializableExtra("CLIP_AVATAR") as String
                    if (avatar.isNotEmpty()) {
                        GlideStaticUtils.displayCircleImage(
                            avatar, R.mipmap.ic_launcher_round, binding.ivAvatar
                        )
                    } else {
                        showMessage("照片选取失败，请重试")
                    }
                }
            }
    }
}